<?php

namespace App\Http\Models;

use App\Http\Models\MemberModel;
use App\Http\Models\VipSettingsModel;
use App\Http\Models\VipLevelModel;
use App\Http\Models\VipLevelExtraModel;
use App\Http\Models\ProductModel;

class VipModel
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 1;

    public static function getLevelExtraInfoByKey( $uid, $key = 'editor_work_numbers' )
    {
        $vip_level = self::getVipLevel($uid);

        $level_info = VipLevelModel::info($vip_level);
        if(!$level_info) return false;

        $level_type = $level_info['user_level_type'];

        $product_info = ProductModel::info($key, $level_type);
        if(!$product_info) return false;

        $config = $product_info['config'];
        $product_id = $product_info['id'];

        $data = VipLevelExtraModel::info($vip_level, $product_id);
        $limit_number = $data['item_value'];
        if($config == 1) $limit_number = ($limit_number == 1) ? true : false;
        
        return $limit_number;
    }

    public static function getVipLevel( $uid )
    {
        $vip_level = MemberModel::is_vip($uid);
        $end_time = VipSettingsModel::getItemValue($uid, 'endtime', 0);

        if($end_time < time()) {
            $vip_level = 0;
        }
        return $vip_level;
    }

    // 更新指定key的值，如果存在，则更新，否则插入
    public static function addItemValue($uid, $key, $value) {
        if(!$uid || !$key || !$value) return false;

        $cond = array('uid'=>$uid, 'status'=>self::STATUS_ACTIVE, 'item_key'=>$key);
        $item = self::where($cond)->first();
        if ($item) {
            $oldValue = (float) $item['item_value'];
            if($value>0) $newValue = $oldValue + abs($value);
            else $newValue = $oldValue - abs($value);
            $newValue = (float) sprintf('%.2f', $newValue);

            $ret = false;
            if($newValue>=0) {
                $fields = ['item_value'=>$newValue, 'modify_time'=>time()];
                $ret = self::where(['id'=>$item['id']])->update($fields);
            }
        } else {
            $ret = false;
            if($value>=0) {
                $data = ['uid'=>$uid, 'item_key'=>$key, 'item_value'=>$value, 'status'=>1,'create_time'=>time(), 'modify_time'=>0];
                $ret = self::create($data);
            }
        }
        if($ret) MemberVipSettingsRecordModel::addRecord($uid, $key, $value);
        return $ret;
    }
}
